import React, { useState, useEffect } from 'react';
import { Upload, Button, message, Typography } from 'antd';
import { UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import { downDoc } from '@/services/ant-design-pro/api'; // 假设你有一个上传文件的 API

const { Paragraph } = Typography;

const FileUpload = ({ value, onChange }) => {
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    console.log(value, 'value');
  }, [value]);

  const handleUpload = async (file) => {
    setLoading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      const response = await downDoc(formData);
      onChange(response.data[0]); // 假设接口返回文件的 URL
      message.success('上传成功');
    } catch (error) {
      console.error(error);
      message.error('上传失败');
    } finally {
      setLoading(false);
    }
  };

  const handleRemove = () => {
    onChange('');
    message.success('文件已删除');
  };

  return (
    <div>
      {value ? (
        <div>
          <Paragraph>
            <a href={value} target="_blank" rel="noopener noreferrer">
              {value}
            </a>
          </Paragraph>
          <Button icon={<DeleteOutlined />} onClick={handleRemove}>
            删除文件
          </Button>
        </div>
      ) : (
        <Upload
          beforeUpload={() => false} // 阻止自动上传
          onChange={({ file }) => handleUpload(file)}
        >
          <Button icon={<UploadOutlined />} loading={loading}>
            上传文件
          </Button>
        </Upload>
      )}
    </div>
  );
};

export default FileUpload;